package com.study.mirrorforest.main.config;

import jakarta.servlet.http.HttpServletResponse;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            // API 场景禁用 CSRF（前后端分离，使用 token 更合适）
            .csrf(csrf -> csrf.disable())
            // CORS 交给 CorsConfig 处理
            .cors(cors -> {})
            // 无状态会话（不使用 JSESSIONID）
            .sessionManagement(sm -> sm.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
            // 放行认证相关接口，其他根据需要调整（当前全部放行，避免重定向到登录页）
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("**").permitAll()
                .anyRequest().permitAll()
            )
            // 禁用默认表单登录与 HTTP Basic，避免 302 到 /login
            .formLogin(form -> form.disable())
            .httpBasic(basic -> basic.disable())
            // 统一未认证返回 JSON 401（若未来有需要保护的接口时生效）
            .exceptionHandling(ex -> ex
                .authenticationEntryPoint((request, response, authException) -> {
                    response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                    response.setContentType("application/json;charset=UTF-8");
                    response.getWriter().write("{\"success\":false,\"code\":401,\"message\":\"Unauthorized\"}");
                })
            );

        return http.build();
    }
}

